package com.xiaoma.h5testdemo.common.dialog

import android.app.Activity
import android.os.Bundle
import android.view.ViewGroup
import androidx.lifecycle.Lifecycle
import com.xiaoma.lib.log.KLog
import java.lang.ref.WeakReference

/**
 * author: liangjingbo
 * date: 2023/12/1
 * describe:
 */
class XmImitateDialogHelper( val lifecycle: Lifecycle) {

    private lateinit var mRoot: ViewGroup
    val mDialogs = HashMap<String, XmImitateDialog<*>>()
    val mDialogStates = ArrayList<DialogState>()
    private var mSavedInstanceState: Bundle? = null
    var mWeakAct: WeakReference<Activity>? = null

    fun attach(activity: Activity, root: ViewGroup, savedInstanceState: Bundle?) {
        KLog.i(TAG, "attach() savedInstanceState: $savedInstanceState")
        mWeakAct = WeakReference(activity)
        mRoot = root
        mSavedInstanceState = savedInstanceState
        if (savedInstanceState != null) {
            restoreState(savedInstanceState)
        }
    }

    /**
     * 恢复状态
     * @param savedInstanceState Bundle
     */
    private fun restoreState(savedInstanceState: Bundle) {
        try {
            val list =
                savedInstanceState.getParcelableArrayList<DialogState>(DIALOG_HELPER_KEY)
            if (list.isNullOrEmpty()) {
                KLog.e(TAG, "restoreState() no need for recovery!!")
                return
            }
            mDialogStates.clear()
            restoreDialog(list)
        } catch (e: Exception) {
            KLog.i(TAG, "restoreState() XM_Exception: $e")
            e.printStackTrace()
        }
    }

    /**
     * 恢复弹窗
     * @param dialogStates ArrayList<DialogState>
     */
    private fun restoreDialog(dialogStates: java.util.ArrayList<DialogState>) {
        KLog.i(TAG, "restoreDialog() dialogStates.size: ${dialogStates.size}")
        if (dialogStates.isEmpty()) {
            KLog.e(TAG, "restoreDialog() dialogStates is empty")
            return
        }
        dialogStates.forEach {
            if (it.canRestore){
                instantiationDialog(it)
            } else {
                KLog.e(TAG, "restoreDialog() ${it.className} set to not require recovery and reconstruction")
            }
        }
    }

    /**
     * 恢复弹窗实例
     * @param dialogState DialogState
     */
    private fun instantiationDialog(dialogState: DialogState) {
        try {
            KLog.i(TAG, "instantiationDialog() dialogState:$dialogState")
            val clz = Class.forName(dialogState.className)
            val newInstance = clz.newInstance() as XmImitateDialog<*>
            newInstance.showDialog(this, getSavedInstanceState())
        } catch (e: Exception) {
            e.printStackTrace()
            KLog.i(TAG, "instantiationDialog() XM_Exception: $e")
        }
    }


    /**
     * 存储状态
     * @param outState Bundle
     */
    fun onSaveInstanceState(outState: Bundle) {
        saveState(outState)
        mDialogs.forEach { (_, u) ->
            u.onSaveInstanceState(outState)
        }
    }

    private fun saveState(outState: Bundle) {
        KLog.i(TAG, "saveState() size: ${mDialogStates.size}")
        if (mDialogStates.size > 0) {
            outState.putParcelableArrayList(DIALOG_HELPER_KEY, mDialogStates)
        }
    }


    private fun getSavedInstanceState(): Bundle? {
        return mSavedInstanceState
    }

    fun getHostView(): ViewGroup {
        return mRoot
    }

    fun onUiModeChange(){
        KLog.i(TAG, "onUiModeChange() ")
        mDialogs.forEach { (_, u) ->
            u.onUiModeChange()
        }
    }

    companion object {
        private val TAG = XmImitateDialogHelper::class.java.simpleName + "_XMTag"
        private const val DIALOG_HELPER_KEY = "dialog_helper_key"

    }
}